#include "StdAfx.h"
#include "TinyConfig.h"

CTinyConfig::CTinyConfig(void):m_xmlInitlized(false),m_parser(NULL)
{
}

CTinyConfig::~CTinyConfig(void)
{
}

std::string CTinyConfig::getRootFolder(void)
{
	//temp static dir for test
	return std::string("C:\\TinyApp");
}

bool CTinyConfig::openXmlFile(std::string filename)
{
	if(m_xmlInitlized == true)
		return false;
	//read config from xml file
	//init xml lib
	try {
		xercesc::XMLPlatformUtils::Initialize();
		m_xmlInitlized = true;
	}
	catch (const xercesc::XMLException& toCatch) {
		char* message = xercesc::XMLString::transcode(toCatch.getMessage());
		//MessageBox(NULL,message,"Exception message is:",MB_OK);
		xercesc::XMLString::release(&message);
		return false;
	}
	//XercesDOMParser*
	m_parser = new xercesc::XercesDOMParser();
	m_parser->setValidationScheme(xercesc::XercesDOMParser::Val_Always);	  // optional.
	m_parser->setDoNamespaces(true);	  // optional

	try {
		m_parser->parse(const_cast<char *>(filename.c_str()));
		//log
		//		logfile<<"version.xml file parsed pass"<<std::endl;
		m_doc=m_parser->getDocument();
		m_walker = 
			m_doc->createTreeWalker((xercesc::DOMNode*)m_doc->getDocumentElement(), xercesc::DOMNodeFilter::SHOW_ELEMENT, NULL, true);

	}
	catch (const xercesc::XMLException& toCatch) {
		char* message = xercesc::XMLString::transcode(toCatch.getMessage());
		//MessageBox(NULL,message,"Exception message is:",MB_OK);
		//strTime = CTime::GetCurrentTime().Format("%Y-%m-%d-%a  %H:%M:%S");
		//logfile<<"XML Parse Error:"<<message<<"at:"<<strTime<<std::endl;
		xercesc::XMLString::release(&message);
		return false;
	}
	catch (const xercesc::DOMException& toCatch) {
		char* message = xercesc::XMLString::transcode(toCatch.msg);
		//MessageBox(NULL,message,"Exception message is:",MB_OK);
		//strTime = CTime::GetCurrentTime().Format("%Y-%m-%d-%a  %H:%M:%S");
		//logfile<<"XML Parse Error:"<<message<<"at:"<<strTime<<std::endl;
		xercesc::XMLString::release(&message);
		return false;
	}
	catch (...) {
		//MessageBox(NULL,"Setting File Task.xml Read Error\n","Exception message is:",MB_OK);
		//strTime = CTime::GetCurrentTime().Format("%Y-%m-%d-%a  %H:%M:%S");
		//logfile<<"XML Parse Error:"<<"at:"<<strTime<<std::endl;
		return false;
	}
	return true;
}

bool CTinyConfig::closeXmLFile()
{
	m_doc->release();
	try {
		xercesc::XMLPlatformUtils::Terminate();
		m_xmlInitlized = false;
	}
	catch (const xercesc::XMLException& toCatch) {
		char* message = xercesc::XMLString::transcode(toCatch.getMessage());
		//MessageBox(NULL,message,"Exception message is:",MB_OK);
		xercesc::XMLString::release(&message);
		return false;
	}
	
	return true;
}

bool CTinyConfig::refreshConfig(void)
{
	readConfigFile(getConfigFileName());
	return false;
}
